<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-left">
        <div class="login-info">
          <h1>环保公众监督系统</h1>
          <p>Environmental Public Supervision System</p>
          <div class="features">
            <div class="feature-item">
              <el-icon><Monitor /></el-icon>
              <span>实时监控环境质量</span>
            </div>
            <div class="feature-item">
              <el-icon><User /></el-icon>
              <span>公众参与监督</span>
            </div>
            <div class="feature-item">
              <el-icon><DataAnalysis /></el-icon>
              <span>数据分析统计</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="login-right">
        <div class="login-form">
          <div class="form-header">
            <h2>登录</h2>
            <p>选择您的角色类型登录系统</p>
          </div>
          
          <!-- 角色选择 -->
          <div class="role-tabs">
            <div 
              class="role-tab" 
              :class="{ active: activeRole === 'admin' }"
              @click="switchRole('admin')"
            >
              <el-icon><UserFilled /></el-icon>
              <span>管理员</span>
            </div>
            <div 
              class="role-tab" 
              :class="{ active: activeRole === 'grid' }"
              @click="switchRole('grid')"
            >
              <el-icon><User /></el-icon>
              <span>网格员</span>
            </div>
            <div 
              class="role-tab" 
              :class="{ active: activeRole === 'supervisor' }"
              @click="switchRole('supervisor')"
            >
              <el-icon><Monitor /></el-icon>
              <span>监督员</span>
            </div>
          </div>
          
          <!-- 登录表单 -->
          <el-form 
            ref="loginFormRef" 
            :model="loginForm" 
            :rules="loginRules" 
            class="login-form-content"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                :placeholder="usernamePlaceholder"
                size="large"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                show-password
                clearable
                @keyup.enter="handleLogin"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                :loading="loading" 
                @click="handleLogin"
                class="login-btn"
              >
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-form-item>
          </el-form>
          
          <!-- 注册链接 -->
          <div class="form-footer" v-if="activeRole === 'supervisor'">
            <p>还没有账号？ 
              <router-link to="/register" class="register-link">
                立即注册
              </router-link>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Monitor, User, DataAnalysis, UserFilled, Lock } from '@element-plus/icons-vue'

export default {
  name: 'Login',
  components: {
    Monitor,
    User,
    DataAnalysis,
    UserFilled,
    Lock
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const { proxy } = getCurrentInstance()
    
    const loginFormRef = ref()
    const activeRole = ref('admin')
    const loading = ref(false)
    
    const loginForm = ref({
      username: '',
      password: ''
    })
    
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }
    
    const usernamePlaceholder = computed(() => {
      const placeholders = {
        admin: '请输入管理员编码',
        grid: '请输入网格员编码',
        supervisor: '请输入监督员编码'
      }
      return placeholders[activeRole.value]
    })
    
    const switchRole = (role) => {
      activeRole.value = role
      loginForm.value.username = ''
      loginForm.value.password = ''
      loginFormRef.value?.clearValidate()
    }
    
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      const valid = await loginFormRef.value.validate()
      if (!valid) return
      
      loading.value = true
      
      try {
        let action = ''
        let loginData = {}
        
        switch (activeRole.value) {
          case 'admin':
            action = 'user/adminLogin'
            loginData = {
              adminCode: loginForm.value.username,
              password: loginForm.value.password
            }
            break
          case 'grid':
            action = 'user/gridMemberLogin'
            loginData = {
              gmCode: loginForm.value.username,
              password: loginForm.value.password
            }
            break
          case 'supervisor':
            action = 'user/supervisorLogin'
            loginData = {
              supervisorCode: loginForm.value.username,
              password: loginForm.value.password
            }
            break
        }
        
        console.log('正在执行登录action:', action)
        console.log('登录数据:', loginData)
        
        const result = await store.dispatch(action, loginData)
        console.log('登录结果:', result)
        
        ElMessage.success('登录成功')
        
        // 临时跳转到首页，因为dashboard页面还未创建
        router.push('/')
        
        // 以下是原来的代码，等dashboard页面创建后再启用
        // const roleRoutes = {
        //   admin: '/admin/dashboard',
        //   grid: '/grid/dashboard',
        //   supervisor: '/supervisor/dashboard'
        // }
        // const targetRoute = roleRoutes[activeRole.value]
        // const redirect = route.query.redirect || targetRoute
        // router.push(redirect)
        
      } catch (error) {
        console.error('Login error:', error)
        console.error('Error type:', typeof error)
        console.error('Error message:', error.message)
        console.error('Error stack:', error.stack)
        
        let errorMessage = '登录失败，请检查用户名和密码'
        
        if (error.message) {
          errorMessage = error.message
        } else if (error.data && error.data.message) {
          errorMessage = error.data.message
        } else if (typeof error === 'string') {
          errorMessage = error
        }
        
        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }
    
    // 如果已经登录，直接跳转到对应页面
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    const userRole = computed(() => store.getters['user/userRole'])
    
    if (isLoggedIn.value) {
      const roleRoutes = {
        'ADMIN': '/admin/dashboard',
        'GRID_MEMBER': '/grid/dashboard',
        'SUPERVISOR': '/supervisor/dashboard'
      }
      router.push(roleRoutes[userRole.value] || '/')
    }
    
    return {
      loginFormRef,
      activeRole,
      loading,
      loginForm,
      loginRules,
      usernamePlaceholder,
      switchRole,
      handleLogin
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-wrapper {
  width: 100%;
  max-width: 1000px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  min-height: 600px;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-info {
  text-align: center;
  
  h1 {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 10px;
  }
  
  p {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 40px;
  }
}

.features {
  .feature-item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    
    .el-icon {
      font-size: 20px;
      margin-right: 10px;
    }
    
    span {
      font-size: 16px;
    }
  }
}

.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-form {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  
  h2 {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}

.role-tabs {
  display: flex;
  margin-bottom: 30px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e1e6f0;
}

.role-tab {
  flex: 1;
  padding: 12px 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #f8f9fa;
  border-right: 1px solid #e1e6f0;
  
  &:last-child {
    border-right: none;
  }
  
  .el-icon {
    display: block;
    font-size: 20px;
    margin-bottom: 4px;
    color: #666;
  }
  
  span {
    font-size: 12px;
    color: #666;
  }
  
  &.active {
    background: #409eff;
    color: #fff;
    
    .el-icon, span {
      color: #fff;
    }
  }
  
  &:hover:not(.active) {
    background: #e6f7ff;
    
    .el-icon, span {
      color: #409eff;
    }
  }
}

.login-form-content {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  
  .login-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
  }
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  
  p {
    color: #666;
    font-size: 14px;
  }
  
  .register-link {
    color: #409eff;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-wrapper {
    flex-direction: column;
    margin: 10px;
  }
  
  .login-left {
    padding: 30px 20px;
  }
  
  .login-info h1 {
    font-size: 24px;
  }
  
  .login-right {
    padding: 30px 20px;
  }
  
  .role-tabs {
    .role-tab {
      padding: 10px 6px;
      
      .el-icon {
        font-size: 18px;
      }
      
      span {
        font-size: 11px;
      }
    }
  }
}
</style> 